#include "SerialPortThread.h"

SerialportThread* SerialportThread::Instance=0;

SerialportThread* SerialportThread::getInstance()
{
    if(Instance==0)
        Instance =new SerialportThread();
    return Instance;
}

SerialportThread::SerialportThread(QObject *parent): QObject(parent)
{
    this->moveToThread(&thread);
    thread.start();
}

void SerialportThread::run()
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString insertSql= "Select IP,Port From IpInfo Where ConnectType='2';";
    query.exec(insertSql);

    QString serialNamePort;
    QString baud="0";
    while(query.next()){
        serialNamePort=query.value("IP").toString();
        baud=query.value("Port").toString();
    }

    serialPort = new QSerialPort(this);
    serialPort->close();

    QSerialPort::BaudRate baudRate;

    if(baud=="115200"){
        baudRate = QSerialPort::Baud115200;
    }
    else if(baud=="4800")
    {
        baudRate = QSerialPort::Baud4800;
    }
    else if(baud=="9600")
    {
        baudRate = QSerialPort::Baud9600;
    }
    else
    {
        return;
    }

    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);
    serialPort->setPortName(serialNamePort);
    serialPort->setBaudRate(baudRate);
    if(serialPort->open(QIODevice::ReadWrite))
    {
        QMLSignal::I().emitCommunicationStatus(0);     // 发信号通知前端

    }else{
        QMLSignal::I().emitCommunicationStatus(1);     // 发信号通知前端

    }
    connect(serialPort,SIGNAL(readyRead()),this,SLOT(serialPortRead_Slot()));// 串口读取
}

// 接收消息
void SerialportThread::serialPortRead_Slot()
{
    QByteArray arr = serialPort->readAll();
    QString str;
    for(int c :arr)
    {
        if(c>=0)
        {
            str += QString(" %1").arg(c, 2, 16, QChar('0')).toUpper();
        }
        else
        {
            str += QString(" %1").arg(c+256, 2, 16, QChar('0')).toUpper();
        }
    }
    str= str.simplified();
    QStringList list=str.split(" ");

}

void SerialportThread::serialPortSend(QByteArray data){
    serialPort->write(data);
}

void SerialportThread::serialclose(){
    if(serialPort->isOpen())
    {
        serialPort->close();
    }
}
